package com.mmloo.manage.controller;

import com.alibaba.fastjson.JSON;
import com.mmloo.common.message.Message;
import com.mmloo.common.model.*;
import com.mmloo.common.page.Pager;
import com.mmloo.common.repository.CURDRepository;
import com.mmloo.common.service.BaseService;
import com.mmloo.common.util.TimeUtil;
import com.mmloo.manage.service.AttributesService;
import com.mmloo.manage.service.GoodsManageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by jessy on 2015/9/25.
 */
@Controller
@RequestMapping("/manage/goods/")
public class GoodsManageController {
    private Logger logger = LoggerFactory.getLogger(GoodsManageController.class);

    @Autowired
    BaseService baseService;

    @Autowired
    GoodsManageService goodsManageService;

    @Autowired
    AttributesService attributesService;

    /**
     * 随机生成商品编号
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "generateNumber",method = RequestMethod.GET)
    public String generateNumber(){
        return new Message(true,"生成商品编号",doProduce()).toJson();
    }

    /**
     * 请求商品添加页面
     * @param id
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "add",method = RequestMethod.GET)
    public String addGoods(String id,Model model) throws Exception {
//        attributesService.test();
        if(!StringUtils.isEmpty(id)) {
            Goods goods = goodsManageService.findGoods(id);
            model.addAttribute("goods",goods);
        }
        return "manage/goods/add";
    }

    /**
     * 请求继续上传图片
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "addPic",method = RequestMethod.GET)
    public String addPic(String id,Model model){
        model.addAttribute("id", id);
        return "manage/goods/uploadPic";
    }

    /**
     * 继续上传图片
     * @param id
     * @param image_urls
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "addPic",method = RequestMethod.POST)
    public String addPic(String id,String image_urls,Model model) throws Exception {
        System.out.println("id ----> " + id + " img ---- > " + image_urls);
        Goods goods = goodsManageService.findGoods(id);
        String img = goods.getImage_urls() + "#" + image_urls;
        goods.setImage_urls(img);
        goodsManageService.update(goods);
        System.out.println("img_urls ---> " + goods.getImage_urls());
        return "redirect:/manage/goods/addPic?id="+id;
    }

    /**
     * 添加商品
     * @param goods
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "add",method = RequestMethod.POST)
    public String addGoods(Goods goods,Model model) throws Exception {
        Goods goods1 = goodsManageService.addGoods(goods);
        Message message = new Message(true,"添加成功！");
        model.addAttribute("message",message);
        return "redirect:/manage/goods/addPic?id="+goods1.getId();
    }

    /**
     * 分页显示商品
     * @param select
     * @param model
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "list")
    public String listGoods(String select,Model model,HttpServletRequest request, HttpServletResponse response,String keyword,String sale_type) throws Exception {
        Pager pager = goodsManageService.getGoodsByPager(new Pager<Goods>(request,response),keyword,sale_type);
        model.addAttribute("pager",pager);
        if(pager.getList().size()!=0) {
            model.addAttribute("message", new Message(true, "成功获取所有商品"));
        }else {
            model.addAttribute("message", new Message(true, "没有此类商品"));
        }
        model.addAttribute("keyword", keyword);
        model.addAttribute("select",select);
        return "manage/goods/list";
    }

    /**
     * 删除指定id的商品
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "delete",method = RequestMethod.GET)
    public String delete(@RequestParam(value = "id",required = true)String id) throws Exception {
        goodsManageService.delete(id);
        return "redirect:/manage/goods/list";
    }
    /**
     * 随机生成商品编号随机号
     * @return
     */
    private static String doProduce() {
        int maxLength = 4;
        String source = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuffer sb = new StringBuffer(100);
        sb.append("g");
        sb.append(TimeUtil.getCurrentTimeInString());
        for (int i = 0; i < maxLength; i++) {
            Random random = new Random();
            final int number =  random.nextInt(source.length());
            sb.append(source.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 初始化添加商品页面
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "init",method = RequestMethod.GET)
    public String init() throws Exception {
        GoodsAttributes goodsAttributes = new GoodsAttributes();
        goodsAttributes.setNumber(doProduce());
        List<Category> categories = attributesService.findAllCategory();
        goodsAttributes.setCategories(categories);
        System.out.println("------------------类别-----------------");
        List<Brand> brands = attributesService.findAllBrand();
        goodsAttributes.setBrands(brands);
        System.out.println("------------------品牌-----------------");
        List<Origin> origins = attributesService.findAllOrigin();
        goodsAttributes.setOrigins(origins);
        System.out.println("-----------------来源-----------------");
        List<City> cities = attributesService.findAllCity();
        goodsAttributes.setCities(cities);
        System.out.println("------------------城市-----------------");
        List<Attribute> attributes = attributesService.findAllAttribute();
        goodsAttributes.setAttributes(attributes);
        System.out.println("------------------属性-----------------");

        List<AttributeOption> attributeOptions = attributesService.findAllAttrOption();
        goodsAttributes.setAttributeOptions(attributeOptions);
        System.out.println("--------------属性选项-----------");

        return JSON.toJSONString(goodsAttributes);
    }

    /**
     * 上传商品图片
     * @param multipartFile
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/upload")
    public String uploadMedia(@RequestParam("mediaFile") MultipartFile multipartFile,
                              HttpServletRequest request,Model model) throws Exception {
        System.out.println("**********************************************");
        String path = request.getSession().getServletContext().getRealPath("/");
        System.out.println("path =  " + path);
        String result = baseService.handleUploadMedia(path, multipartFile);
        Message message = new Message(true,"上传图片成功！",result);
        model.addAttribute("message",message);
        return message.toJson();
    }

    @RequestMapping(value = "/imageAdd",method = RequestMethod.POST)
    public String addImage(String goodsId,String url,Model model) throws Exception {
        System.out.println("goodsId:" + goodsId);
        System.out.println("url:" + url);
        Goods goods = goodsManageService.findGoods(goodsId);
        goods.setImage_urls(url);
        goodsManageService.update(goods);
        model.addAttribute("goods",goods);
        return "redirect:/manage/goods/add";
    }

    @ResponseBody
    @RequestMapping(value = "list/json",method = RequestMethod.GET)
    public String listGoodsByJson(String select,Model model,HttpServletRequest request, HttpServletResponse response,String keyword,String sale_type) throws Exception {
        Pager pager = goodsManageService.getGoodsByPager(new Pager<Goods>(request, response), keyword, sale_type);
//        model.addAttribute("pager", pager);
        if(pager.getList().size()!=0) {
            pager.setPager_end(pager.toString());
            System.out.println("success===========>");
            return new Message(true, "成功获取所有商品",pager).toJson();
//            return JSON.toJSONString(string);
        }else {
            return new Message(true, "没有此类商品").toJson();
        }
        /*return "manage/promotion/returnBuy/add";*/

    }
}
